<template>
  <div class="supply-list">
    <div style="padding:1em;margin-bottom:1em;background:#fff">
      <a-row>
        <a-col :span="4">
          <a-input v-model="searchForm.supplier" placeholder="请输入供应商名"/>
        </a-col>
        <a-col :span="4">
          <a-button style="margin-left:10px" type="primary" icon="search" @click="toSearch">Search</a-button>
        </a-col>
      </a-row>
    </div>
    <el-card shadow="never">
      <div>
        <a-button type="primary" @click="addSupplier">添加</a-button>
        <a-button :disabled="table.selected.length === 1?false:true" type="primary" @click="uploadFile"><a-icon type="arrow-up"/>附件</a-button>
      </div>
      <div style="margin-top:10px">
        <a-table
          size="small"
          ref="suppliers"
          :rowKey="record => record.id"
          :loading="table.loading"
          :pagination="table.pagination"
          :data-source="table.data"
          :customRow="rowClick"
          :row-selection="{ selectedRowKeys: table.selected, onChange: selectionChange}"
        >
          <a-table-column
            :width="150"
            key="supplier"
            title="供应商"
            data-index="supplier"
            align="center"
            ellipsis="true"
          >
            <template slot-scope="text">
              <a-tooltip placement="topLeft" :title="text+''">
                <span @click="handleCopy(text, $event)">{{ text }}</span>
              </a-tooltip>
            </template>
          </a-table-column>
          <a-table-column :width="120" key="telephone" title="联系方式" data-index="telephone" :ellipsis="true" align="center">
            <template slot-scope="text">
              <a-tooltip placement="topLeft" :title="text+''">
                <span @click="handleCopy(text, $event)">{{ text }}</span>
              </a-tooltip>
            </template>
          </a-table-column>
          <a-table-column :width="120" key="address" title="地址" data-index="address" :ellipsis="true" align="center">
            <template slot-scope="text">
              <a-tooltip placement="topLeft">
                <span @click="handleCopy(text, $event)">{{ text }}</span>
              </a-tooltip>
            </template>
          </a-table-column>
          <a-table-column :width="120" key="remark" title="备注" data-index="remark" :ellipsis="true" align="center" />
          <a-table-column :width="80" key="sysFiles" title="附件" data-index="sysFiles" align="center">
          <template slot-scope="t">
            <el-tag v-for="(item, key) in t" :key="key" effect="plain" type="primary">
              <a style="display: block" class="ellipsis" :href="item.url" :key="item.url" target="_blank">附件</a>
            </el-tag>
          </template>
        </a-table-column>
          <a-table-column :width="120" key="addOperator" title="录入人" data-index="addOperator" :ellipsis="true" align="center" />
          <a-table-column :width="120" key="addTime" title="录入时间" data-index="addTime" align="center" :sorter="(a, b) => a.addTime.localeCompare(b.addTime)">
            <template slot-scope="text">
              {{dateTimeFormat(text)}}
            </template>
          </a-table-column>
          <a-table-column :width="200" fixed="right" align="center" key="action" title="操作">
            <template slot-scope="text, record">
              <el-button @click.stop="editTemplate(record)" type="primary" size="mini" icon="el-icon-edit"></el-button>
              <el-button @click.stop="deleteTemplate(record.id)" type="danger" size="mini" icon="el-icon-delete"></el-button>
              <el-button @click.stop="addAccount(record.id)" type="info" size="mini" icon="el-icon-plus"></el-button>
            </template>
          </a-table-column>
        </a-table>
      </div>
    </el-card>

    <el-dialog v-el-drag-dialog :title="dialog.title" :visible.sync="dialog.visible" @close="handleClose">
      <el-form ref="form" :rules="rules" :model="dialog.form" status-icon>
        <el-row :gutter="10">
          <el-col :sm="24" :lg="12">
            <el-form-item label="供应商" label-width="80px" prop="supplier">
              <el-input type="text" size="small" v-model="dialog.form.supplier"/>
            </el-form-item>
          </el-col>
          <el-col :sm="24" :lg="12">
            <el-form-item label="联系方式" label-width="80px" prop="telephone">
              <el-input type="text" size="small" v-model="dialog.form.telephone"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :sm="24" :lg="12">
            <el-form-item label="地址" label-width="80px" prop="address">
              <el-input type="text" size="small" v-model="dialog.form.address"/>
            </el-form-item>
          </el-col>
          <el-col :sm="24" :lg="12">
            <el-form-item label="备注" label-width="80px" prop="remark">
              <el-input type="text" size="small" v-model="dialog.form.remark"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialog.visible = false">取消</el-button>
        <el-button type="primary" size="small" @click="dialogSubmit('form')">提交</el-button>
      </div>
    </el-dialog>

    <!--新添账户模态框-->
    <el-dialog v-el-drag-dialog :title="accountDialog.title" :visible.sync="accountDialog.visible">
      <el-form :model="accountDialog.form">
        <a-row type="flex" justify="start" v-for="(data,index) in accountDialog.form.dataList">
          <a-col :span="6">
            <el-form-item label="开户银行" label-width="80px" size="small" prop="bankOfDeposit">
              <el-input type="text" v-model="data.bankOfDeposit"></el-input>
            </el-form-item>
          </a-col>
          <a-col :span="8">
            <el-form-item label="开户账号" label-width="80px" size="small" prop="account">
              <el-input type="text" v-model="data.account"></el-input>
            </el-form-item>
          </a-col>
          <a-col :span="6">
            <el-form-item label="备注" label-width="80px" size="small" prop="remark">
              <el-input type="text" v-model="data.remark"></el-input>
            </el-form-item>
          </a-col>
          <a-col :span="1">
            <el-form-item>
              <a-button type="danger" ghost @click="delRowCustom(index)" icon="minus"></a-button>
            </el-form-item>
          </a-col>
        </a-row>
        <a-button @click="addRowCustom" style="width: 98%;border-style: dashed" icon="plus">新增</a-button>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="accountDialog.visible = false">取 消</el-button>
        <el-button type="primary" size="small" :loading="accountDialog.subLoading" @click="submitHandler()">提 交</el-button>
      </div>
    </el-dialog>

    <!--上传附件-->
    <el-dialog v-el-drag-dialog title="上传附件" :visible.sync="supply.visible">
      <a-upload-dragger
        name="file"
        :multiple="true"
        :action="fileUploadUrl"
        withCredentials
        list-type="picture"
        :before-upload="beforeUpload"
        :file-list="fileList"
        @change="uploadStatusChange"
        :headers="headers"
      >
        <p class="ant-upload-drag-icon">
          <a-icon type="inbox" />
        </p>
        <p class="ant-upload-text" style="color: #40a9ff">
          上传项目文件
        </p>
        <p class="ant-upload-text">
          点击或者拖拽文件来上传
        </p>
        <p class="ant-upload-hint">
          支持单个或多个文件上传. 单个文件请不要超过12M
        </p>
      </a-upload-dragger>
      <div slot="footer" class="dialog-footer">
        <a-button type="primary" @click="submit">提交</a-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import '@/styles/auto-style.css'
  import { dateTimeFormat } from '@/utils/format'
  import { getAction, postActionByJson, postActionByQueryString } from '@/api/manage'
  import { beforeUpload, uploadStatusChange } from '@/utils/upload'
  import elDragDialog from '@/directive/el-drag-dialog'
  import { onFilterDropdownVisibleChange, onFilter, handleReset, handleSearch} from '@/utils/column-search'
  import clip from '@/utils/clipboard'
  import { getToken } from '@/utils/auth'

  export default {
    directives: { elDragDialog },
    data() {
      const fileUploadUrl = process.env.VUE_APP_BASE_API + 'file/uploadCache'

      const scopedSlots = {
        filterDropdown: 'filterDropdown',
        filterIcon: 'filterIcon',
        customRender: 'customRender',
      };
      var validNotRepeat = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('不能为空'));
        }
        if(this.validMark){
          postActionByQueryString(this.url.supplyCheck,{keyword:this.dialog.form.supplier})
          .then(resp =>{
            if (resp.data == 1){
              callback(new Error('该供货商已存在'))
            }else {
              callback()
            }
          })
        }else{
          callback()
        }
      };
      return {
        headers: {"X-Token": getToken()},
        //附件上传
        fileList: [],
        supply: {
          visible: false,
        },
        fileUploadUrl,
        table:{
          selected: [],
          validMark: true,
          data: [],
          loading: false,
          pagination: {
            showTotal: total => `共 ${total} 条结果`,
            showQuickJumper: true,
            showSizeChanger: true,
            pageSizeOptions: ['5', '10', '20', '50'],
            pageNum: 1,
            pageSize: 10,
            total: 0,
            onChange: (pageNum) => {
              this.table.pagination.pageNum = pageNum
              this.toSearch()
            },
            onShowSizeChange: (pageNum, pageSize) => {
              this.table.pagination.pageSize = pageSize
              this.toSearch()
            } // 改变每页数量时更新显示
          }
        },
        searchForm: {},
        supplierId: '',
        accountDialog: {
          visible: false,
          form: {dataList: []},
          subLoading: false
        },
        suppliers: [],
        suppliersLoading: false,
        dialog: {
          title: '',
          visible: false,
          form: {
          }
        },
        rules: {
          supplier: [
            { validator: validNotRepeat, trigger: 'blur'}
          ],
        },
        url: {
          saveOrUpdateSupplierBank: '/supply/supplier/saveOrUpdateSupplierBank',
          findSupplierBankAccount: '/supply/supplier/findSupplierBankAccount',
          supplyCheck: '/supply/supplier/supplyCheck',
          findSupplier: '/supply/supplier/findSupplier',
          deleteSupplier: '/supply/supplier/deleteSupplier',
          findByOtherId: '/file/findByOtherId',
          uploadSupplyQualification: '/supply/supplier/uploadSupplyQualification'
        },
        scopedSlots,
      }
    },
    created() {
      this.init()
    },
    methods: {
      submit(){
        const fileList = this.fileList.map(item => {
            return { id: item.id, otherId: this.table.selected[0], name: item.name, url: item.url}
          })
        postActionByJson(this.url.uploadSupplyQualification, {sysFiles: fileList})
        .then(resp=>{
          this.$message.success(resp.message + "个文件上传成功!")
        }).catch(()=>{

        }).finally(()=>{
          this.supply.visible = false
          this.toSearch()
        })
      },
      uploadStatusChange,
      beforeUpload,
      uploadFile(){
        if(this.table.selected.length === 1){
          this.supply.visible = true
          this.fileList = []
          getAction(this.url.findByOtherId,{otherId: this.table.selected[0], type: 9})
          .then(resp => {
            resp.data.map(item => {
              let response = item
              response.error = 0
              response.fileId = response.id
              response.fileName = response.name
              this.fileList.push({
                uid: 0-item.id,
                name: item.name,
                status: 'done',
                response: response,
                url: response.url
              })
            })
          })
        }else{
          this.$message({type:'warning', message: '请选择一家供应商'})
        }
      },
      rowClick(row, index) {
        return {
          on: {
            click: () => {
              let index = this.table.selected.indexOf(row.id)
              if(index === -1){
                this.table.selected.push(row.id)
              }else{
                this.table.selected.splice(index, 1)
              }
            }
          }
        }
      },
      selectionChange(){

      },
      handleClose(){
        //清楚表单验证
        this.$refs['form'].resetFields();
      },
      handleCopy(text, event) {
        clip(text, event)
      },
      submitHandler(){
        let arr = []
        let supplierId = this.supplierId
        this.accountDialog.form.dataList.forEach(function(item, index) {
          let obj = {}
          obj.id = item.id
          obj.bankOfDeposit = item.bankOfDeposit
          obj.supplierId = supplierId
          obj.account = item.account
          obj.remark = item.remark
          arr.push(obj)
        })
        if (arr.length === 0){
          this.$message.error('请勿全部删除')
          this.accountDialog.visible = false
          return
        }
        postActionByJson(this.url.saveOrUpdateSupplierBank, arr)
        .then(resp =>{
          this.$message.success(resp.data + '条提交成功')
        }).catch(()=>{
          this.$message.error('提交失败')
        }).finally(()=>{
          this.accountDialog.visible = false
        })
      },
      addRowCustom() {
        this.accountDialog.form.dataList.push({})
      },
      delRowCustom(index) {
        this.accountDialog.form.dataList.splice(index, 1)
      },
      addAccount(id){
        this.accountDialog.form = {dataList: []}
        this.supplierId = id
        getAction(this.url.findSupplierBankAccount, {supplierId: id})
        .then(resp =>{
          this.accountDialog.form.dataList = resp.data
        }).catch(()=>{
          this.$message.error('查询失败')
        }).finally(()=>{
          this.accountDialog.visible = true
        })
      },
      init() {
        this.toSearch()
      },
      toSearch() {
        this.table.loading = true
        this.searchForm.pageNum = this.table.pagination.pageNum
        this.searchForm.pageSize = this.table.pagination.pageSize
        getAction(this.url.findSupplier, this.searchForm)
        .then(resp => {
          this.table.data = resp.data.records
          this.table.pagination.pageNum = resp.data.current
          this.table.pagination.pageSize = resp.data.size
          this.table.pagination.total = resp.data.total
        }).catch((e)=>{
        })
        .finally(()=>{
          this.table.loading = false
        })
      },
      addSupplier() {
        this.dialog.title = '新增'
        this.dialog.visible = true
        this.dialog.form = {}
        this.validMark = true
      },
      editTemplate(record) {
        this.dialog.title = '修改'
        this.dialog.visible = true
        this.dialog.form = record
        this.validMark = false
      },
      deleteTemplate(id) {
        this.$confirm('是否确定删除？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          getAction(this.url.deleteSupplier,{id: id})
          .then(resp => {
            this.$message.success(resp.message + '条删除成功')
          }).catch(()=>{})
          .finally(()=>{
            this.toSearch()
          })
        })
      },
      dialogSubmit(form) {
        this.$refs[form].validate((valid) => {
          if (valid) {
            postActionByQueryString('/supply/supplier/saveOrUpdate', this.dialog.form)
            .then(resp => {
              this.$message({ type: 'success', message: resp.message })
            }).catch((e)=>{
            }).finally(()=>{
              this.dialog.visible = false
              this.toSearch()
            })
          }else {
            return false
          }
        })
      },
      dateTimeFormat,
      onFilterDropdownVisibleChange,
      onFilter,
      handleReset,
      handleSearch,
    }
  }
</script>

<style lang="scss" scoped>
  .supply-list {
    margin: 10px 10px 0px 10px;
    /deep/.el-form-item__content{
      height:auto;
      line-height:32px;
      margin-left:90px!important
    }
  }
</style>
